package pack01_wordcount;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author lilulu
 * @date 2023/2/10 21:14
 * 集群运行，参数动态获取，可以写成shell脚本
 */
public class JobMain {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, URISyntaxException {

        //配置文件对象
        Configuration configuration = new Configuration();
        //创建作业实例
        Job job = Job.getInstance(configuration, "wordcount");
        // 设置作业驱动类
        job.setJarByClass(JobMain.class);


        //1:配置job的输入数据路径,一行行读取
        FileInputFormat.addInputPath(job, new Path(args[0]));

        //2：设置job的自定义Mapper类是哪个类
        job.setMapperClass(WordCountMapper.class);

        //3: 设置job的Mapper的K2，V2数据类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //4:设置job的自定义reducer类是哪个类
        job.setReducerClass(WordCountReduce.class);

        //5:设置job的Reducer的K3，V3数据类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);


        //6:配置job的输出数据路径,该路径不能存在，否则报错
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        //判断输出路径是否存在 如果存在删除
//        FileSystem fileSystem = FileSystem.get(new URI("file:///"), configuration);
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://node1:8020"), configuration);
        boolean flag = fileSystem.exists(new Path(args[1]));
        if(flag == true){
            fileSystem.delete(new Path(args[1]),true);
        }

        //提交作业并等待执行完成
        boolean bl = job.waitForCompletion(true);
        //程序退出
        System.exit(bl ? 0 : 1);
    }

}
